<?php
class Position extends AppModel {
    var $name = 'Position';
    var $validate = array(
        'name' => array(
            'required' => array(
                'required' => true,
                'allowEmpty' => false,
                'rule' => 'notEmpty',
                'message' => 'Wajib diisi',
                'last' => true
            ),
            'maxlength' => array(
                'rule' => array('maxlength', 100),
                'message' => 'Wajib diisi'
            )
        ),
        'special' => array(
            'rule' => 'vApproval',
            'message' => 'Hanya satu user yang dapat menjadi approval'
        )
    );
    var $actsAs = array('Tree');
    
    function vApproval($field) {
        if ( !$this->id ) {
            return true;
        }
        
        return $this->find('count', array(
            'conditions' => array(
                'id <>' => $this->id,
                'special' => 1
            )
        )) == 0;
    }

    /**
     * We need to override this callback
     * to update verified_by field on act_lists
     */
    function afterSave($created) {
        if ( !$created ) {
            $verified_by = $this->data['Position']['parent_id'];
            App::import('User');
            $User = new User;
            $users = $User->find('all', array(
                'conditions' => array('position_id' => $this->id), 'recursive' => -1,
                'fields' => array('id')
            ));
            $creators = array();
            foreach ( $users as $user ) {
                $creators[] = $user['User']['id'];
            }
            $creators = implode(', ', $creators);
            
            $this->query("UPDATE act_lists SET verified_by = {$verified_by} WHERE created_by IN ({$creators})");
        }
        
        return true;
    }
    
    function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array()) {
        $records = $this->find('all', compact(
            'conditions', 'fields', 'order', 'limit',
            'page', 'recursive', 'group', 'contain'
            )
        );
        
        foreach ( $records as $k => $r ) {
            $_children = array();
            $children = $this->children($r['Position']['id'], true, array('name'));
            foreach ( $children as $child ) {
                $_children[] = $child['Position']['name'];
            }
            $records[$k]['Position']['verfied_positions'] = implode(', ', $_children);
        }
        return $records;
    }
}
?>
